<?php
/*
 * [task_builder id='FieldsetBuilder' label='fieldset' tableclasses='table-bordered,table-striped,table-hover,table-condensed']
 *
 */

namespace WebApper\Shortcode;

class TaskBuilder extends \WebApper\Shortcode {
	
    /**
     * Define shortcode properties
     *
     */
	protected $shortcode = 'task_builder';
	protected $defaults = array(
		'id' => null,			// The unique ID to use for the shortcode. Default: none. Required.
		'usercap' => 'edit_plugins',	// The minimum user capability required to access the Fieldset Builder. OPTIONS: 'logged_out', 'read', 'edit_posts', 'edit_others_posts', 'edit_users', 'edit_pages', 'edit_plugins'. Default 'edit_plugins'.
		'label' => 'Task Template',			// The fieldset label to display. Default: 'Fieldset'.
		'tableclasses' => 'table-bordered,table-striped,table-hover,table-condensed',  // Adjust how the DataTable will display. Default: 'table-bordered,table-striped,table-hover,table-condensed'.
	);

    /**
     * Handles the add post shortcode
     *
     * @param array $atts
     */
    public function shortcode( $atts ) {

		// Get shortcode attributes
			extract( shortcode_atts( $this->defaults, $atts ) );

		// Ouput datatable HTML & Javascript
			?>
            <hr />
            <div class="alert alert-info fade in">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                <strong>How To!</strong> Use this tool to create fields to use in shortcodes. Records(or posts) are created and managed with shortcodes. Shortcodes must have fields included to create and edit posts with. Rows are selectable. Click on the add, edit, or delete button to get started.
            </div>
			<table id="<?php echo $id; ?>_datatable" class="table <?php echo str_replace(",", " ", $tableclasses); ?>">
				<thead>
					<tr>
						<th rowspan="2">ID</th>
						<th rowspan="2">name</th>
						<th rowspan="2">Subject</th>
						<th rowspan="2">Description</th>
						<th colspan="2">Due In</th>
						<th rowspan="2">Assign to</th>
						<th rowspan="2">Task status</th>
					</tr>
					<tr>
						<th>#</th>
						<th>unit</th>
					</tr>
				</thead>
				<tbody>
					<?php
					global $wpdb, $webapper;
					$web_apper_taskTemplates = $wpdb->get_results( "SELECT * FROM {$webapper->tables->taskTemplates}" );

					foreach ( $web_apper_taskTemplates as $taskTemplate ) :
						echo '<tr>',
								 '<td>', $taskTemplate->ID, '</td>',
								 '<td>', stripslashes( $taskTemplate->name ), '</td>',
								 '<td>', stripslashes( $taskTemplate->subject ), '</td>',
								 '<td>', stripslashes( $taskTemplate->description ), '</td>',
								 '<td>', $taskTemplate->due_in, '</td>',
								 '<td>', stripslashes( $taskTemplate->due_unit ), '</td>',
								 '<td>', stripslashes( $taskTemplate->assign_to_user ), '</td>',
								 '<td>', stripslashes( $taskTemplate->status ), '</td>',
							 '</tr>';
					endforeach;
					?>
				</tbody>
			</table>

			<script type="text/javascript">
				// Store Commonly manipulated DOM nodes as objects
				nForm = jQuery('#<?php echo $id; ?>');
				nFormTask = jQuery('input[name="web_apper_task"]', nForm);
				nModal = jQuery('.modal', nForm);
				nModalHeader = jQuery('.modal-header h3', nModal)
				nModalBody = jQuery('.modal-body', nModal);
				nModalClose = jQuery('.modal-footer [data-dismiss="modal"]', nModal)
				nModalSaveBtn = jQuery('.modal-footer #save', nModal)
				nModalUpdateBtn = jQuery('.modal-footer #update', nModal)
				nModalDeleteBtn = jQuery('.modal-footer #delete', nModal)
				nModalElements = jQuery('.modal-body>*', nModal);
				nDeleteWarning = jQuery('#deleteWarning', nModal);
				nTable = jQuery('#<?php echo $id; ?>_datatable');
				nRowAlert = jQuery('#infoModal');
				
				jQuery(document).ready(function($) {

					// Initialize dataTable
					oTable = $(nTable).dataTable({
						<?php
							// Build the sDom parameter for dataTables
							global $template;
							if ( stristr($template, 'fullwidth') ) :
								$spanA = 6; $spanB = 6;
							else :
								$spanA = 4; $spanB = 5;
							endif;
							echo "'sDom': \"<'row'<'span".$spanA."'EC><'span".$spanB."'fl>r>t<'row'<'span".$spanA."'i><'span".$spanB."'p>>\",\n";
						?>
						'sPaginationType': 'bootstrap',
						'oLanguage': {
							'sLengthMenu': 'records per page <select>'+
							'<option value="10">10</option>'+
							'<option value="20">20</option>'+
							'<option value="30">30</option>'+
							'<option value="40">40</option>'+
							'<option value="50">50</option>'+
							'<option value="100">100</option>'+
							'</select>'
						},
						'aoColumnDefs': [ { 'bVisible': false, 'aTargets': [ 0, 7 ] } ],
						"aaSorting": [ [5,'asc'], [17,'asc'] ],
						'oColVis': {
							'buttonText': 'Columns',
							'bRestore': true,
							'sAlign': 'left',
							'sSize': 'css',
							'aiExclude': [ 0 ]
						},
					});

				});

				// Handle response from ajax post
				function parseResponse<?php echo $id; ?>(response) {
					var result = jQuery.parseJSON(response);  // Parse response
console.log(result);
					if ( result.success ) {  // If ajax returns a successful save
						if ( result.task == 'add' ) {  // If we added a row
							jQuery('input[name="web_apper_id"]', nForm).val( result.ID );  // Prepend the returned record ID to the array before adding to the dataTable
							var formValues = nForm.getFormValues();  // Get array of form values
							oTable.fnAddDataAndDisplay(formValues);  // Add row to table
							nForm.clearForm();  // Clear form values
						} else if ( result.task == 'update' ) {  // If we updated a row
							var rowPosition = oTable.fnGetPosition( jQuery('tr.row_selected')[0] );  // Get the position of the currently selected row
							var formValues = nForm.getFormValues();  // Get array of form values
							oTable.fnUpdate( formValues, rowPosition ); // Update the dataTable row
						} else if ( result.task == 'delete' ) {  // If we deleted a row
							nDeleteWarning.css('display', 'none');  // Hide the delete warning
							nModalDeleteBtn.css('display', 'none');  // Hide the modal submit button
							var rowPosition = oTable.fnGetPosition( jQuery('tr.row_selected')[0] );  // Get the position of the currently selected row
							oTable.fnDeleteRow( rowPosition );
						}
					}
					resetModalButtons();
					nModalBody.prepend(result.htmlalert);  // Show and alert
				}

			</script>
            <?php

		// Configure form settings
			$this->config_form( $atts );
			
		// Build the form
			$form = new \PFBC\Form($id);
			$form->configure( $this->formConfig );
			$form->addElement(new \PFBC\Element\Hidden('web_apper_form', $id));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_nonce', wp_create_nonce( 'WebApperAwesomeness!87' )));
			$form->addElement(new \PFBC\Element\Hidden('action', 'web_apper' . $this->shortcode));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_task', 'add'));
			// Form Modal header
			$form->addElement(new \PFBC\Element\ModalHeading($label));
			$form->addElement(new \PFBC\Element\HTML('<div id="deleteWarning"><span class="label label-important pull-left">Delete ' . $label . '</span><p>&nbsp;You are about to delete a ' . $label . '. Are you sure you want to do this?</p></div>'));
			// Form Modal body
			$form->addElement(new \PFBC\Element\Hidden('web_apper_id'));
			$form->addElement(new \PFBC\Element\Textbox('Name:', 'task_template_name', array(
				"required" => 1,
				'placeholder' => 'Task Template Name',
			)));
			$form->addElement(new \PFBC\Element\Textbox('Subject:', 'task_subject', array(
				'placeholder' => 'Task Subject',
			)));
			$form->addElement(new \PFBC\Element\Textarea('Description:', 'task_description', array(
				'placeholder' => 'Task Description',
			)));
			$form->addElement(new \PFBC\Element\Number('Due In:', 'task_due_in'));
			$form->addElement(new \PFBC\Element\Select('', 'task_due_in_unit', array(
				'hours', 'days', 'weeks', 'months'
			)));
			$form->addElement(new \PFBC\Element\Select('Assign to', 'task_assign_to_user', array(
				'rotate_users', 'least_to_do'
			) ));
			$form->addElement(new \PFBC\Element\Select('Status', 'task_status', array(
				'assigned', 'in-progress', 'complete', 'archived'
			)));
			// Form Modal footer
			$form->addElement(new \PFBC\Element\Button('Save', 'submit', array(
				'id' => 'save',
				'data-loading-text' => 'Saving...'
			)));
			$form->addElement(new \PFBC\Element\Button('Update', 'submit', array(
				'id' => 'update',
				'data-loading-text' => 'Updating...'
			)));
			$form->addElement(new \PFBC\Element\Button('Delete', 'submit', array(
				'id' => 'delete',
				'class' => 'btn btn-danger',
				'data-loading-text' => 'Deleting...'
			)));
            $form->render();  // Output the form

	}

    /**
     * Add new record
     *
     * @since 1.0
     */
	public function add_record() {
		global $wpdb, $webapper;
		$result = $wpdb->insert( 
			$webapper->tables->taskTemplates,
			array( 
				'name' => $_POST['task_template_name'],
				'subject' => $_POST['task_subject'],
				'description' => $_POST['task_description'],
				'due_in' => $_POST['task_due_in'],
				'due_unit' => $_POST['task_due_in_unit'],
				'assign_to_user' => $_POST['task_assign_to_user'],
				'status' => $_POST['task_status']
			),
			array( '%s', '%s', '%s', '%d', '%s', '%s', '%s' ) 
		);
		if ( $result ) :	
			return $this->sendResponse( 'Task template saved.', 'alert-success', 'Hurray!', true, $wpdb->insert_id );  // Send Response
		else :
			return $this->sendResponse( 'There was a problem saving the task template. Please Try again.', 'alert-error', 'Oh snap!', false );  // Send Response
		  endif;
	}

    /**
     * Update a record
     *
     * @since 1.0
     */
	public function update_record() {
		global $wpdb, $webapper;
		$result = $wpdb->update(
			$webapper->tables->taskTemplates,
			array( 
				'name' => $_POST['task_template_name'],
				'subject' => $_POST['task_subject'],
				'description' => $_POST['task_description'],
				'due_in' => $_POST['task_due_in'],
				'due_unit' => $_POST['task_due_in_unit'],
				'assign_to_user' => $_POST['task_assign_to_user'],
				'status' => $_POST['task_status']
			),
			array( 'ID' => $_POST['web_apper_id'] ),
			array( '%s', '%s', '%s', '%d', '%s', '%s', '%s' ) 
		);
		if ( $result === 0 ) :	
			return $this->sendResponse( 'The task template was not updated because you haven\'t made any changes.', 'alert-info', 'Heads Up!', true );  // Send Response
		elseif ( $result ) :	
			return $this->sendResponse( 'Task template saved.', 'alert-success', 'Hurray!', true, $wpdb->insert_id );  // Send Response
		else :
			return $this->sendResponse( 'There was a problem saving the task template. Please Try again.', 'alert-error', 'Oh snap!', false );  // Send Response
		endif;
	}

    /**
     * Delete a record
     *
     * @since 1.0
     */
	public function delete_record() {
		global $wpdb, $webapper;
		$result = $wpdb->query(
			$wpdb->prepare( "DELETE FROM {$webapper->tables->taskTemplates} WHERE id = %d", $_POST['web_apper_id'] )
		);
		if ( $result ) :	
			return $this->sendResponse( 'Task template deleted.', 'alert-success', 'Hurray!', true );  // Send Response
		else :
			return $this->sendResponse( 'There was a problem deleting the task template. Please Try again.', 'alert-error', 'Oh snap!', false );  // Send Response
		endif;
	}
	
}

$initialize = new TaskBuilder(); 

?>